extends Node2D

@export var min_speed: float = 885.0;
@export var max_speed: float = 915.0;
@export var challenge: float = 0.3;

var total_length: float = 0.0;
var generated_checkpoints: int = 0;

@onready var min_label: Label = $数据UI/最低速度
@onready var max_label: Label = $数据UI/最高速度
@onready var current_label: Label = $数据UI/当前速度
@onready var complete_label: Label = $数据UI/完成情况

@onready var pressed: AudioStreamPlayer = $音乐音效/点击音效
@onready var 游戏结束_失败_: AudioStreamPlayer = $"音乐音效/游戏结束（失败）"
@onready var 游戏结束_通关_: AudioStreamPlayer = $"音乐音效/游戏结束（通关）"
@onready var 超速警告: AudioStreamPlayer = $音乐音效/超速警告
@onready var 本次行程: Label = $失败UI/Control/Panel/ex关结束/本次行程
@onready var 得分比: Label = $失败UI/Control/Panel/ex关结束/得分比

@onready var uipro: CanvasLayer = $关卡介绍
@onready var 失败ui: CanvasLayer = $失败UI
@onready var 成功ui: CanvasLayer = $成功UI

@onready var tile_map_layer: TileMapLayer = $TileMapLayer
var TileSetNumber = 0;
var TileRoad = Vector2i(0, 19);
@onready var player: CharacterBody2D = $邮车;
var tile_length = 710.0;
var last_trigger_x = 0.0;
var initial_setup_done = false;
@onready var target_area: Area2D = $检查点
var area_spawn_chance = 0.4;
var spawn_offset = 1700.0;

var speed_flag=false;
var speed_flags_count=0;
var end_defeat=false;

var speed_over_timer: Timer = Timer.new()
var has_recorded_overrun = false

var tile_y_offset = 0.0;

var time_accumulator: float = 0.0;
var last_player_x: float = 0.0;
var text123=0;
func _ready() -> void:
	print("脚本载入成功");
	last_trigger_x = player.position.x;
	last_player_x = player.position.x;
	generate_road_tiles();
	initial_setup_done = true;
	update_complete_label();
	
	speed_over_timer.wait_time = 2.0
	speed_over_timer.one_shot = true
	add_child(speed_over_timer)
	speed_over_timer.timeout.connect(_on_speed_over_timeout)
	失败ui.visible = false
	成功ui.visible = false
	get_tree().paused=true

func _pressed():
	pressed.play();

func UI_pro():
	get_tree().paused=false;
	uipro.visible=false;
	
func update_complete_label() -> void:
	# 直接读取player的投递数，同步到UI
	var mailed_count = 0
	if "player_mailed" in player:
		mailed_count = player.player_mailed
	complete_label.text = "已投递：%d" % [mailed_count];
	min_label.text = "%.1f" % min_speed;
	max_label.text = "%.1f" % max_speed;
	current_label.text = "%.1f" % player.current_speed;

func generate_road_tiles() -> void:
	tile_map_layer.clear();
	
	var player_world_pos = player.global_position;
	
	var offsets = [
		-tile_length*2,
		-tile_length,
		0.0,
		tile_length,
		tile_length*2,
		tile_length*3,
		tile_length*4
	];
	
	for offset_x in offsets:
		var target_world_pos = Vector2(
			player_world_pos.x + offset_x,
			player_world_pos.y + tile_y_offset
		);
		var tile_pos = world_to_tile_grid(target_world_pos);
		tile_map_layer.set_cell(tile_pos, TileSetNumber, TileRoad);

func world_to_tile_grid(world_pos: Vector2) -> Vector2i:
	var local_pos = tile_map_layer.to_local(world_pos);
	var grid_pos = tile_map_layer.local_to_map(local_pos);
	grid_pos.y = 0;
	return grid_pos;

func _process(delta: float) -> void:
	if end_defeat:
		return;
	if not initial_setup_done:
		return;
	
	update_total_length();
	
	time_accumulator += delta;
	if time_accumulator >= 1.0:
		min_speed += challenge;
		max_speed += challenge;
		player.current_speed += challenge;
		time_accumulator = 0.0;
		print("速度递增！当前区间：[%.1f, %.1f]，当前速度：%.1f" % [min_speed, max_speed, player.current_speed]);
	
	monitor_player_speed()
	if player.position.x - last_trigger_x >= tile_length:
		generate_road_tiles();
		last_trigger_x += tile_length;
		try_duplicate_area();
	update_complete_label();

func update_total_length() -> void:
	var current_x = player.position.x;
	var moved_distance = current_x - last_player_x;
	if moved_distance > 0:
		total_length += moved_distance;
	last_player_x = current_x;

func monitor_player_speed() -> void:
	var current_speed = player.current_speed
	if current_speed < min_speed or current_speed > max_speed:
		speed_flag = true
		if not has_recorded_overrun:
			speed_flags_count += 1
			has_recorded_overrun = true
			print("速度超限！当前超限次数：", speed_flags_count)
		if speed_over_timer.is_stopped():
			超速警告.play();
			speed_over_timer.start()
			print("速度超限，开始2秒倒计时...")
	else:
		超速警告.stop()
		speed_flag = false
		has_recorded_overrun = false
		if not speed_over_timer.is_stopped():
			speed_over_timer.stop()
			print("速度恢复正常，倒计时已重置")

func _on_speed_over_timeout() -> void:
	本次行程.text="移动距离：%.1fk" % [total_length/100.0]
	
	if not end_defeat and speed_flag:
		end_defeat = true
		游戏结束_通关_.play();
		
		# 直接读取原始数据，打印「已投递数量/生成数量」
		var mailed_count = 0
		if "player_mailed" in player:
			mailed_count = player.player_mailed
		得分比.text="得分比：%d/%d" % [mailed_count, generated_checkpoints]
		print("⚠️  游戏失败！")
		print("=== 最终统计 ===")
		print("移动距离：%.1fk" % [total_length/100.0])
		print("生成检查点总数：%d" % generated_checkpoints)
		print("已投递数量：%d" % mailed_count)
		print("得分比：%d/%d" % [mailed_count, generated_checkpoints])  # 核心需求：直接显示分数格式
		print("===============")
		
		get_tree().paused = true
		失败ui.visible = true

func restart_current_scene() -> void:
	pressed.play();
	await get_tree().create_timer(0.5).timeout
	get_tree().paused = false
	total_length = 0.0;
	generated_checkpoints = 0;
	time_accumulator = 0.0;
	speed_flags_count = 0;
	end_defeat = false;
	has_recorded_overrun = false;
	last_player_x = 0.0;
	min_speed = 885.0;
	max_speed = 915.0;
	player.current_speed = (min_speed + max_speed) / 2;
	# 重置投递数
	if "player_mailed" in player:
		player.player_mailed = 0
	var current_scene_path = get_tree().current_scene.scene_file_path
	get_tree().change_scene_to_file(current_scene_path)
	print("✅ 场景已重新开始！所有统计变量已重置")

func try_duplicate_area() -> void:
	if end_defeat:
		return;
	if not target_area:
		print("警告：未找到作为模板的Area2D节点，请检查节点名称");
		return;
	if randf() < area_spawn_chance:
		var new_area = target_area.duplicate();
		new_area.name = "Area2D_Spawned_" + str(randi_range(1000, 9999));
		var target_pos = Vector2(
			player.global_position.x + spawn_offset,
			player.global_position.y + tile_y_offset
		);
		new_area.global_position = target_pos;
		new_area.visible = true;
		add_child(new_area);
		generated_checkpoints += 1;
		# 实时打印生成情况
		var current_mailed = player.player_mailed if "player_mailed" in player else 0
		print("✅ 生成检查点！累计：%d，当前投递数：%d" % [generated_checkpoints, current_mailed])
		new_area.call_deferred("queue_free_in", 3.0);

func queue_free_in(delay: float) -> void:
	await get_tree().create_timer(delay).timeout;
	queue_free();
	print("清理检查点：", name)

func goto_select() -> void:
	get_tree().paused = false
	pressed.play();
	await get_tree().create_timer(0.5).timeout
	get_tree().change_scene_to_file("res://场景/选关界面.tscn");

func back_menu():
	pressed.play();
	await get_tree().create_timer(0.5).timeout
	get_tree().paused=false;
	get_tree().change_scene_to_file("res://场景/主菜单.tscn")
